<style lang="postcss" scoped>
.home-container {
}
</style>
<template>
  <section class="home-container">
    <MasterPage title>
      <div slot="searchContent" class="search-content-slot">
        <Form :model="formItem" :label-width="80">
          <Row>
            <Col span="4">
              <FormItem label="工号">
                <Input v-model="formItem.workNo"></Input>
              </FormItem>
            </Col>
            <Col span="4">
              <FormItem label="姓名">
                <Input v-model="formItem.name"></Input>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
      <div slot="search">
        <Button style="margin-right:5px;" type="primary" icon="md-add" @click="new1()">添加</Button>
        <Button
          style="margin-right:5px;"
          type="info"
          icon="md-cloud-upload"
          @click="excelImport()"
        >批量导入</Button>
        <!-- <Button
          style="margin-right:5px;"
          type="error"
          icon="md-remove"
          @click="removeSelection()"
        >删除</Button>-->
        <Button style="margin-right:5px;" type="success" @click="authSelection()">一键授权</Button>
        <Button type="info" @click="classModel = true">关联班级</Button>
      </div>
      <div slot="btns">
        <Button type="info" icon="ios-search" @click="search()">查询</Button>
      </div>
      <div slot="paddingContent">
        <Table :columns="columns1" :data="data1" @on-selection-change="onSelectionChange"></Table>
        <Modal :title="title" v-model="modal1" class-name="vertical-center-modal" :closable="false">
          <Form ref="formValidate" :model="formData" :label-width="80" :rules="ruleValidate">
            <FormItem label="工号" prop="workNo">
              <Input v-model="formData.workNo" :disabled="editdisable"></Input>
            </FormItem>
            <FormItem label="姓名" prop="name">
              <Input v-model="formData.name"></Input>
            </FormItem>
            <FormItem label="登录账号" prop="loginId">
              <Input v-model="formData.loginId" :disabled="editdisable"></Input>
            </FormItem>
            <FormItem label="登录密码" prop="password">
              <Input v-model="formData.password"></Input>
            </FormItem>
            <FormItem label="性别" prop="sex">
              <RadioGroup v-model="formData.sex">
                <Radio label="1">男</Radio>
                <Radio label="2">女</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem label="出生日期">
              <DatePicker
                type="date"
                placeholder="请选择"
                v-model="formData.birthday"
                style="width:100%"
              ></DatePicker>
            </FormItem>
            <FormItem label="入职日期">
              <DatePicker
                type="date"
                placeholder="请选择"
                v-model="formData.hiredate"
                style="width:100%"
              ></DatePicker>
            </FormItem>
            <FormItem label="职称">
              <RadioGroup v-model="formData.position">
                <Radio label="1">教授</Radio>
                <Radio label="2">职工</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem label="联系电话">
              <Input v-model="formData.phone" :disabled="editdisable" number></Input>
            </FormItem>
          </Form>
          <div slot="footer">
            <Button type="text" size="large" @click="model1Closed()">取消</Button>
            <Button type="primary" size="large" @click="ok()">确定</Button>
          </div>
        </Modal>
        <Modal title="EXCEL导入" v-model="excelModel" class-name="vertical-center-modal">
          <Upload
            ref="upload"
            type="drag"
            :action="GLOBAL.updateUrl+'/gm_teacher/importTeacherExcel'"
            :on-success="handleSuccess"
            :format="['xlsx','xls']"
            :on-format-error="handleFormatError"
          >
            <div style="padding: 20px 0">
              <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
              <p>点击或拖拽文件上传</p>
            </div>
          </Upload>
          <!-- <div v-if="file !== null">Upload file: {{ file.name }}</div> -->
          <div slot="footer">
            <!-- <Button
              type="text"
              @click="upload"
              :loading="loadingStatus"
            >{{ loadingStatus ? 'Uploading' : 'Click to upload' }}</Button>-->
          </div>
        </Modal>
        <Modal title="授权" v-model="authModel" class-name="vertical-center-modal">
          <Tree :data="roleList" show-checkbox></Tree>
          <div slot="footer">
            <Button type="text" size="large" @click="authModel = false">取消</Button>
            <Button type="primary" size="large" @click="bindRole()">确定</Button>
          </div>
        </Modal>
        <Modal title="班级" v-model="classModel" class-name="vertical-center-modal">
          <!-- <Select v-model="classId" style="width:200px">
            <Option v-for="item in classList" :value="item.id" :key="item.id" :label="item.name"></Option>
          </Select>-->
          <Tree :data="classList" show-checkbox></Tree>
          <div slot="footer">
            <Button type="text" size="large" @click="classModel = false">取消</Button>
            <Button type="primary" size="large" @click="bindClass()">确定</Button>
          </div>
        </Modal>
      </div>
      <div slot="pager">
        <!-- <Page :total="data1.length"/> -->
        <Page
          :total="pageTotal"
          :current="formItem.page"
          :page-size="formItem.size"
          show-total
          show-sizer
          placement="top"
          @on-change="handlePage"
          @on-page-size-change="handlePageSize"
        />
      </div>
    </MasterPage>
  </section>
</template>
<script>
import MasterPage from '@/components/Master'
import { pageList, add, update, authRole, batchAuthRole, bindClass, remove } from '@/services/teacher'
import { list as getRoleList } from '@/services/role'
import { pageList as getClassListByYear } from '@/services/class'

export default {
  components: {
    MasterPage
  },
  async mounted() {
    console.log("teacher")
    await this.search()
    //获取当前学年班级
    let date = new Date();
    let year = date.getFullYear();
    let pageData = await getClassListByYear({ year })
    this.classList = pageData.list.map(p => Object.assign(p, { title: p.name }))
  },
  methods: {
    handleFormatError(file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: `文件:${file.name}格式不正确，请上传.xls,.xlsx文件。`
      })
    },
    handleSuccess(res, file) {
      if (res && res.success) {
        this.$Message.info("数据导入成功");
      } else {
        this.$Notice.error({ title: '数据导入失败', desc: res.message });
        this.$refs.upload.clearFiles()
      }
    },
    async bindClass() {
      if (!this.selection || this.selection.length == 0) {
        this.$Message.error("请选择需要关联的教师")
        return
      }
      let classIds = this.classList.map(r => {
        if (r.checked) return r.id
      })
      classIds = classIds.filter(r => r)
      classIds = classIds.join(",")
      try {
        await bindClass(this.teacherIds, classIds)
      } catch (err) {
        this.$Notice.error({ title: '操作失败', desc: err });
      }
    },
    authSelection() {
      if (!this.selection || this.selection.length == 0) {
        this.$Message.error("请选择需要授权的账户")
        return
      }
      this.setAuthRole()
    },
    async bindRole() {
      try {
        console.log(this.roleList)
        let roleIds = this.roleList.map(r => {
          if (r.checked) return r.id
        })
        roleIds = roleIds.filter(r => r)
        roleIds = roleIds.join(",")

        if (!this.authId) {
          //批量授权
          this.$Modal.confirm({
            title: "警告",
            content: "批量授权会覆盖账户原有角色，是否确认？",
            onOk: async () => {
              await batchAuthRole(this.teacherIds, roleIds)
              this.authModelClosed()
            }
          })
        } else {
          await authRole(this.authId, roleIds)
          this.authModelClosed()
        }
      } catch (err) {
        this.$Notice.error({ title: '操作失败', desc: err });
      }
    },
    async authModelClosed() {
      this.$Message.info("操作成功");
      this.authId = null
      this.selection = []
      this.authModel = false
      await this.search(this.formItem)
    },
    excelImport() {
      this.excelModel = true
      this.files = []
    },
    async removeSelection() {
      //批量删除
      try {
        // await generate(this.generateData)
        this.$Message.info("操作成功");
        await this.search(this.formItem)
      } catch (err) {
        this.$Notice.error({ title: '操作失败', desc: err });
      }
    },
    onSelectionChange(selection) {
      this.selection = selection
      let teacherIds = this.selection.map(s => s.id)
      this.teacherIds = teacherIds.join(",")
    },
    edit(row) {
      this.formData = Object.assign({}, row)
      this.title = "编辑"
      this.editdisable = true
      this.modal1 = true
    },
    async remove1(row) {
      console.log(row)
      this.$Modal.confirm({
        title: "警告",
        content: "删除后无法恢复，是否确认？",
        onOk: async () => {
          try {
            await remove(row.id)
            this.$Message.info("操作成功");
            this.search()
          } catch (err) {
            this.$Notice.error({ title: '操作失败', desc: err });
          }
        }
      })

    },
    async new1() {
      this.formData.sex = 1
      this.title = "新增"
      this.editdisable = false
      this.modal1 = true
    },
    async ok() {
      let valid = await this.$refs.formValidate.validate()
      if (!valid) return
      try {
        if (this.title == '新增') {
          //新增
          await add(this.formData)
        } else {
          //修改
          await update(this.formData)
        }
        this.$Message.info("操作成功");
        this.model1Closed()
        await this.search(this.formItem)
      } catch (err) {
        this.$Notice.error({ title: '操作失败', desc: err });
      }
    },
    model1Closed() {
      this.modal1 = false
      this.formData = {}
      this.$refs.formValidate.resetFields()
    },
    async search() {
      let { count, list } = await pageList(this.formItem)
      this.data1 = list
      this.pageTotal = count
    },
    async handlePage(n) {
      this.formItem.page = n
      await this.search()
    },
    async handlePageSize(n) {
      this.formItem.size = n
      await this.search()
    },
    setAuthRole(row = {}) {
      console.log(row)
      this.authId = row.id
      let roleIds = !row.roleIds ? [] : row.roleIds.split(",")
      console.log(roleIds)
      getRoleList().then(list => {
        this.roleList = list.map(r => {
          r.title = r.roleName
          if (roleIds.length > 0 && roleIds.indexOf(r.id.toString()) >= 0)
            r.checked = true
          return r
        })
      })
      this.authModel = true

    }

  },
  data() {
    const validateWorkNo = (rule, value, callback) => {
      console.log(value)
      this.formData.loginId = value
      if (!this.formData.password) this.formData.password = "123456"
      callback();
    };
    return {
      file: null,
      loadingStatus: false,
      classModel: false,
      classList: [],
      teacherIds: "",
      roleList: [],
      authId: "",
      authModel: false,
      files: [],
      excelModel: false,
      editdisable: false,
      selection: [],
      modal1: false,
      title: "",
      formData: {},
      pageTotal: 15,
      pageNum: 1,
      pageSize: 10,
      formItem: {},
      columns1: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '工号',
          key: 'workNo'
        },
        {
          title: '姓名',
          key: 'name'
        },
        {
          title: '登录账号',
          key: 'loginId'
        },
        {
          title: '性别',
          key: 'sex',
          render: (h, params) => {
            return h('p', params.row.sex == 1 ? "男" : "女");
          }
        },
        {
          title: '职称',
          key: 'position',
          render: (h, params) => {
            return h('p', params.row.position == 1 ? "教授" : "职工");
          }
        },
        {
          title: '入职日期',
          key: 'hiredate',
          width: 100
        },
        {
          title: '出生日期',
          key: 'birthday',
          width: 100
        },
        {
          title: '拥有角色',
          key: 'roleNames'
        },
        {
          title: '教授班级',
          key: 'classNames'
        },
        {
          title: '操作',
          // key: 'action',
          width: 180,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.edit(params.row)
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.remove1(params.row)
                  }
                }
              }, '删除'),
              h('Button', {
                props: {
                  type: 'success',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.setAuthRole(params.row)
                  }
                }
              }, '授权'),
            ]);
          }
        }
      ],
      ruleValidate: {
        workNo: [
          { required: true, message: '必填', trigger: 'blur' },
          { validator: validateWorkNo, trigger: 'change' }
        ],
        name: [
          { required: true, message: '必填', trigger: 'change' }
        ],
        loginId: [
          { required: true, message: '必填', trigger: 'change' }
        ],
        password: [
          { required: true, message: '必填', trigger: 'change' }
        ],
        sex: [
          { required: true, message: '必填', trigger: 'blur' }
        ],
      },
      data1: []
    }
  },
}
</script>
